package com.market.manage.service.impl;

import com.market.manage.mapper.ArticleMapper;
import com.market.manage.mapper.UsersMapper;
import com.market.manage.po.Article;
import com.market.manage.service.MailService;
import com.market.manage.service.UploadLoadService;
import com.market.utils.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;

@Service
public class UploadLoadServiceImpl implements UploadLoadService {
    @Value("${imgHost}")
    private String imgHost;

    @Resource
    private MailService mailServiceImpl;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Override
    public String upload(MultipartFile file) {
        String fileName = FileUtil.getFileName(file);
        String location = "D:\\images\\";
        String path = location + fileName;
        String imgUrl = "";
        // 查看路径是否存在，不存在就创建
        if (!new File(location).exists()) {
            boolean mkdirs = new File(location).mkdirs();
        }
        try {
            file.transferTo(new File(path));
            imgUrl = imgHost + "/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgUrl;
    }

    /**
     * 发表文章
     *
     * @param html
     * @param ids
     */
    @Override
    public void publicArticle(String title, String html, Long[] ids) {
        StringBuilder sb = new StringBuilder();
        //发送邮件给指定的联系人
        for (Long id : ids) {
            String mail = usersMapper.selById(id);
            try {
                mailServiceImpl.sendHtmlMail(mail, "考勤管理", html);
                sb.append(id);
                sb.append(",");
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        //存储到数据库
        Article article = new Article();
        //去除最后一个逗号
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        article.setTitle(title);
        article.setContent(html);
        article.setUserId(sb.toString());
        article.setCreated(new Timestamp(System.currentTimeMillis()));
        article.setStatus("0");
        articleMapper.insArticle(article);
    }

}
